package com.kf.bigbluebook.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kf.bigbluebook.common.BaseResponse;
import com.kf.bigbluebook.common.ErrorCode;
import com.kf.bigbluebook.common.ResultUntils;
import com.kf.bigbluebook.constant.UserConstant;
import com.kf.bigbluebook.exception.BusinessException;
import com.kf.bigbluebook.model.po.User;
import com.kf.bigbluebook.model.request.UserLoginRequest;
import com.kf.bigbluebook.model.request.UserRegisterRequest;
import com.kf.bigbluebook.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
public class UserController {
    @Autowired
    UserService userService;

    /***
     * 用户注册
     * @param userRegisterRequest 账户 密码 确认密码
     * @return userId
     */
    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> register(@RequestBody UserRegisterRequest userRegisterRequest) {
        //判断请求是否为空
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        //判断参数是否为空
        if (StringUtils.isAnyBlank(userAccount, password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        //执行注册业务
        Long result = userService.register(userAccount, password, checkPassword);
        return ResultUntils.success(result);
    }

    /***
     * 用户登录
     * @param userLoginRequest 账户 密码
     * @param request 请求
     * @return user信息
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public BaseResponse<User> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"登录参数为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String password = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, password)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"用户名或密码为空");
        }
        User user = userService.login(userAccount, password, request);
        return ResultUntils.success(user);
    }

    /***
     * 根据用户名搜索用户
     * @param username
     * @param request
     * @return
     */
    @ApiOperation(value = "用户搜索")
    @GetMapping("/search")
    public BaseResponse<List<User>> search(String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream()
                .map(user -> userService.getSafetyUser(user))
                .collect(Collectors.toList());
        return ResultUntils.success(list);
    }

    /***
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object object = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (object == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        //获取session中用户id，查询数据库返回当前登录用户信息
        User user = (User) object;
        User safetyUser = userService.getSafetyUser(userService.getById(user.getId()));
        return ResultUntils.success(safetyUser);
    }

    /***
     * 注销
     * @param request
     * @return
     */
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public BaseResponse loginOut(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        int result = userService.logout(request);
        return ResultUntils.success(result);
    }

    /**
     * 删除用户
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "删除用户")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestParam long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUntils.success(b);
    }

    /***
     * 根据标签搜索用户
     * @param tagNameList
     * @return
     */
    @ApiOperation(value = "根据标签搜索用户")
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchByTags(@RequestParam(required = false) List<String> tagNameList) {
        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        List<User> userList = userService.searchUserByTags(tagNameList);
        return ResultUntils.success(userList);
    }

    /***
     * 推荐用户
     * @return
     */
    @ApiOperation(value = "推荐用户")
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        Page<User> userPage = userService.pageList(pageSize,pageNum,loginUser);
        return ResultUntils.success(userPage);
    }

    /***
     * 修改用户信息
     * @param user
     * @param request
     * @return
     */
    @ApiOperation("修改用户信息")
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest request){
        //判断参数是否为空
        if(user == null){
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        //更新用户
        int i = userService.updateUser(user,loginUser);
        return ResultUntils.success(i);
    }
    /**
     * 获取最匹配的用户
     *
     * @param num
     * @param request
     * @return
     */
    @ApiOperation(value = "获取匹配用户")
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        User user = userService.getLoginUser(request);
        return ResultUntils.success(userService.matchUsers(num, user));
    }
}
